#include <ds/parted_buffer.h>
#include <mm/valloc.h>
#include <mm/mm.h>

pbuffer_t* pbuffer_add(pbuffer_t** pb, void* data, size_t size) {
    pbuffer_t* new = valloc(sizeof(pbuffer_t));
    *new = (pbuffer_t) {
        .data = data,
        .size = size,
        .paddr = (void*)get_pa((uptr)data),
        .acc_size = pbuffer_size(*pb) + size,
    };

    if (*pb) {
        list_append(&(*pb)->part, &new->part);
    } else {
        list_head_init(&new->part);
        *pb = new;
    }
    return new;
}

void pbuffer_free(pbuffer_t* pb) {
    pbuffer_t* pos, * n;
    list_for_each(pos, n, &pb->part, part) {
        vfree(pos);
    }
    vfree(pos);
}

size_t pbuffer_size(pbuffer_t* pb) {
    if (!pb) {
        return 0;
    }

    pbuffer_t* last = list_entry(pb->part.prev, pbuffer_t, part);
    return last->acc_size;
}